package com.wenqiner.requesttool.view.base;

import com.alibaba.fastjson2.JSON;
import com.wenqiner.requesttool.core.business.lingyin.ParamData;
import com.wenqiner.requesttool.domain.HttpResponseData;
import com.wenqiner.requesttool.util.AESEncryptUtil;
import com.wenqiner.requesttool.util.CommonUtil;
import com.wenqiner.requesttool.util.DigitalSignatureUtil;
import com.wenqiner.requesttool.util.RSAUtil;

/**
 * @author rhf
 * @date 2023-03-28
 **/
public interface OuterParamProcess {

    /**
     * 请求加密
     *
     * @param publicKey  公钥
     * @param privateKey 私钥
     * @param param      参数
     * @param time       时间戳
     * @return java.lang.String
     * @author rhf
     */
    default String requestEncrypt(String publicKey, String privateKey, String param, String time) throws Exception {
        String random = CommonUtil.getValue();
        String code = RSAUtil.encryptByPublicKey(publicKey, random);
        String data = AESEncryptUtil.encryptBase64(param, random);
        String sign = DigitalSignatureUtil.createSign(param, privateKey, "&time=", time);
        ParamData paramData = new ParamData();
        paramData.setEncryptedData(data);
        paramData.setSecretCode(code);
        paramData.setSign(sign);
        return CommonUtil.formatJson(paramData);
    }

    /**
     * 解密验签
     *
     * @param publicKey        公钥
     * @param privateKey       私钥
     * @param httpResponseData 响应
     * @return com.wenqiner.requesttool.core.business.lingyin.ParamData
     * @author rhf
     */
    default ParamData responseDecrypt(String publicKey, String privateKey, HttpResponseData<String> httpResponseData) throws Exception {
        ParamData res = JSON.parseObject(httpResponseData.getData(), ParamData.class);

        if (res.isSuccess()) {
            String code = RSAUtil.decryptByPrivateKey(privateKey, res.getSecretCode());
            String data = AESEncryptUtil.decryptBase64(res.getEncryptedData(), code);
            res.setData(data);
        }
        return res;
    }
}
